package com.openstack4j.qx.rest;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient.OSClientV2;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.compute.Action;
import org.openstack4j.model.compute.RebootType;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.compute.ServerCreate;
import org.openstack4j.openstack.OSFactory;

import com.openstack4j.qx.pojo.BaseResp;
import com.openstack4j.qx.pojo.VMInfoSet;
import com.openstack4j.qx.pojo.VMResp;
import com.openstack4j.qx.pojo.VMStatusResp;

/**
 * 虚拟机VM rest接口服务
 * 
 * @author Lynne
 *
 */
@Path("/VMRest")
public class VMRest {

	/**
	 * 创建虚拟机
	 * 
	 * @param request
	 * @return
	 */
	@POST
	@Path("/CreateVMReq")
	@Produces(MediaType.APPLICATION_JSON)
	public BaseResp CreateVMReq(@Context HttpServletRequest request) {
		String ParamFlag = request.getParameter("ParamFlag");
		String ResourceTemplateID = request.getParameter("ResourceTemplateID");

		String VMResourceInfo_VMName = request.getParameter("VMResourceInfo.VMName");
		String VMResourceInfo_CPUNum = request.getParameter("VMResourceInfo.CPUNum");
		String VMResourceInfo_MemorySize = request.getParameter("VMResourceInfo.MemorySize");
		String VMResourceInfo_OSDiskType = request.getParameter("VMResourceInfo.OSDiskType");
		String VMResourceInfo_OSSize = request.getParameter("VMResourceInfo.OSSize");
		String VMResourceInfo_VEthAdaNum = request.getParameter("VMResourceInfo.VEthAdaNum");
		String VMResourceInfo_VSCSIAdaNum = request.getParameter("VMResourceInfo.VSCSIAdaNum");
		String VMResourceInfo_VMOS = request.getParameter("VMResourceInfo.VMOS");
		
		String AppID = request.getParameter("AppID");
		String AppName = request.getParameter("AppName");
		String Count = request.getParameter("Count");
		String Security = request.getParameter("Security");

		System.out.println("ParamFlag="+ParamFlag);
		System.out.println("ResourceTemplateID="+ResourceTemplateID);
		System.out.println("VMResourceInfo_VMName="+VMResourceInfo_VMName);
		System.out.println("VMResourceInfo_CPUNum="+VMResourceInfo_CPUNum);
		System.out.println("VMResourceInfo_MemorySize="+VMResourceInfo_MemorySize);
		System.out.println("VMResourceInfo_OSDiskType="+VMResourceInfo_OSDiskType);
		System.out.println("VMResourceInfo_OSSize="+VMResourceInfo_OSSize);
		System.out.println("VMResourceInfo_VEthAdaNum="+VMResourceInfo_VEthAdaNum);
		System.out.println("VMResourceInfo_VSCSIAdaNum="+VMResourceInfo_VSCSIAdaNum);
		System.out.println("VMResourceInfo_VMOS="+VMResourceInfo_VMOS);
		System.out.println("AppID="+AppID);
		System.out.println("AppName="+AppName);
		System.out.println("Count="+Count);
		System.out.println("Security="+Security);

		//实例化创建虚拟机返回  实体对象
		VMResp resp = new VMResp();
		List<VMInfoSet> list_vMResp=new ArrayList();
		
		
		try {
			// 业务代码编写
						
			//登录认证
			OSClientV2 os = OSFactory.builderV2()
	                .endpoint("http://10.50.0.11:5000/v2.0")
	                .credentials("admin","ADMIN_PASS")
	                .tenantName("admin")
	                .authenticate();
			
			//string count 转换成 int countVM
			Integer CountVM = Integer.parseInt(Count);
			
			
			for(int i=0;i<CountVM;i++){
		
				//创建虚拟机
				List<String> list_network=new ArrayList();
				list_network.add("127c1dd2-0218-4eaf-83b1-09b31c7ddade");
			
				//create server
				ServerCreate sc = Builders.server().name("baater2").networks(list_network)
					.flavor("2").image("3ee9e4d2-356d-4f6d-ac0e-6252d5c6930d").build();
				//boot server
				Server server = os.compute().servers().boot(sc);
			
			
				
				//实例化返回值
				VMInfoSet vm=new VMInfoSet();
				
				//设置返回值VMResp中的值
				vm.setOperationIP(server.getAccessIPv4());
				
				//判断VM status 的string值改为int
				if(server.getVmState()=="active"){
					vm.setStatus(2);
				}else if(server.getVmState()=="building"){
					vm.setStatus(1);
				}else{
					vm.setStatus(0);
				}
				
				vm.setVlanID(server.getAccessIPv4());
				vm.setVMName(server.getTenantId());
				
				list_vMResp.add(vm);
			
			
			
			}
			
			//VMResp的所有值放回到VMResp对象中
			resp.setVMInfo(list_vMResp);
			return resp;

		} catch (Exception e) {
			e.printStackTrace();
			// 异常信息
			resp.setFaultstring(e.getMessage());
		}
		return resp;
	}

	/**
	 * 操作虚拟机
	 * 该接口用于对资源池管理中的虚拟机进行启动、暂停、恢复、停止、重启操作
	 * 操作类型1：启动 2：暂停 3：恢复 4：停止 5：重启
	 * @param request
	 * @return
	 */
	@GET
	@Path("/ActVMReq")
	@Produces(MediaType.APPLICATION_JSON)
	public BaseResp ActVMReq(@Context HttpServletRequest request) {
		String VMID = request.getParameter("VMID");
		String ActTypeRequested = request.getParameter("ActType");
		
		System.out.println("VMID=" + VMID);
		System.out.println("ActType=" + ActTypeRequested);
		
		//实例化返回值信息
		BaseResp baseResp = new BaseResp();
		try{
			//登录认证
			OSClientV2 os = OSFactory.builderV2()
	                .endpoint("http://10.50.0.11:5000/v2.0")
	                .credentials("admin","ADMIN_PASS")
	                .tenantName("admin")
	                .authenticate();
			//通过参数虚拟机ID，对其做操作		
			Server server = os.compute().servers().get(VMID);
			
		
			
			/*
			 * 操作虚拟机
			 * 1：启动 start server
				2：暂停 
				3：恢复
				4：停止
				5：重启
			 */
			
			
			//String ActTypeRequested 转换成 int ActType 
			Integer ActType = Integer.parseInt(ActTypeRequested);
			
			
			String result = null;
			if(ActType == 1){
				//  start a Server    
				ActionResponse ar = os.compute().servers().action(server.getId(), Action.START);
				//判断虚拟机操作，并设置返回值。
				if(ar.isSuccess()){
					result = "成功启动了虚拟机"+server.getId();
				}else{
					result = ar.getFault();    
					// 返回值为：  Cannot 'start' instance 9a7baf31-d925-4998-a41b-468a98a8449f while it is in vm_state active
				}
				
			}else if (ActType == 2){
				// Suspend a Server
				ActionResponse ar = os.compute().servers().action(server.getId(), Action.SUSPEND);
				//判断虚拟机操作，并设置返回值。
				if(ar.isSuccess()){
					result = "成功暂停了虚拟机"+server.getId();
				}else{
					result = ar.getFault();
				}
			}else if (ActType == 3){
				// Resume a Server
				ActionResponse ar = os.compute().servers().action(server.getId(), Action.RESUME);
				//判断虚拟机操作，并设置返回值。
				if(ar.isSuccess()){
					result = "成功回复虚拟机"+server.getId();
				}else{
					result = ar.getFault();
				}
				
			}else if (ActType == 4){
				// stop a Server
				ActionResponse ar = os.compute().servers().action(server.getId(), Action.STOP);
				//判断虚拟机操作，并设置返回值。
				if(ar.isSuccess()){
					result = "成功停止虚拟机"+server.getId();
				}else{
					result = ar.getFault();
				}
				
			}else if (ActType == 5){
				// reboot a Server
				ActionResponse ar = os.compute().servers().reboot(server.getId(), RebootType.SOFT);
				//判断虚拟机操作，并设置返回值。
				if(ar.isSuccess()){    //&& server.getVmState() == 'avtive';
					result = "成功重启虚拟机"+server.getId();
				}else{
					result = ar.getFault();
				}
				
			}
			
			//给返回值赋值
			baseResp.setFaultstring(result);
			//返回对象值
			return baseResp;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			baseResp.setFaultstring(e.getMessage());
		}
		return baseResp;
	}
	
	
	
	/**
	 * 删除虚拟机
	 * @param request
	 * @return
	 */
	@GET
	@Path("/DeleteVMReq")
	@Produces(MediaType.APPLICATION_JSON)
	public BaseResp DeleteVMReq(@Context HttpServletRequest request) {
		String VMID = request.getParameter("VMID");
		System.out.println("VMID=" + VMID);
		
		//实例化返回值对象
        BaseResp baseResp = new BaseResp(); 
        
		try{
			//登录认证
			OSClientV2 os = OSFactory.builderV2()
	                .endpoint("http://10.50.0.11:5000/v2.0")
	                .credentials("admin","ADMIN_PASS")
	                .tenantName("admin")
	                .authenticate();
			//删除指定ID的虚拟机
			ActionResponse ar = os.compute().servers().delete(VMID);
			
			
	        //定义一个result局部变量
	        String result = null;
	           //判断返回值
		       if(ar.isSuccess()){
		    	   result="删除虚拟机成功！";
		       }
	        
			
			
	        //设置返回值
	        baseResp.setFaultstring(result);
			
	        //返回内容
			return baseResp;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			baseResp.setFaultstring(e.getMessage());
		}
		return baseResp;
	}
	
	
	
	
	/**
	 * 更改虚拟机配置
	 * @param request
	 * @return
	 */
	@POST
	@Path("/ModifyVMReq")
	@Produces(MediaType.APPLICATION_JSON)
	public BaseResp ModifyVMReq(@Context HttpServletRequest request) {
		String VMID = request.getParameter("VMID");
		String VMResourceInfo_VMName = request.getParameter("VMResourceInfo.VMName");
		String VMResourceInfo_CPUNum = request.getParameter("VMResourceInfo.CPUNum");
		String VMResourceInfo_MemorySize = request.getParameter("VMResourceInfo.MemorySize");
		String VMResourceInfo_OSDiskType = request.getParameter("VMResourceInfo.OSDiskType");
		String VMResourceInfo_OSSize = request.getParameter("VMResourceInfo.OSSize");
		String VMResourceInfo_VEthAdaNum = request.getParameter("VMResourceInfo.VEthAdaNum");
		String VMResourceInfo_VSCSIAdaNum = request.getParameter("VMResourceInfo.VSCSIAdaNum");
		String VMResourceInfo_VMOS = request.getParameter("VMResourceInfo.VMOS");
		
		System.out.println("VMID=" + VMID);
		System.out.println("VMResourceInfo_VMName="+VMResourceInfo_VMName);
		System.out.println("VMResourceInfo_CPUNum="+VMResourceInfo_CPUNum);
		System.out.println("VMResourceInfo_MemorySize="+VMResourceInfo_MemorySize);
		System.out.println("VMResourceInfo_OSDiskType="+VMResourceInfo_OSDiskType);
		System.out.println("VMResourceInfo_OSSize="+VMResourceInfo_OSSize);
		System.out.println("VMResourceInfo_VEthAdaNum="+VMResourceInfo_VEthAdaNum);
		System.out.println("VMResourceInfo_VSCSIAdaNum="+VMResourceInfo_VSCSIAdaNum);
		System.out.println("VMResourceInfo_VMOS="+VMResourceInfo_VMOS);
		
		BaseResp resp = new BaseResp();
		try{
			//业务代码
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			resp.setFaultstring(e.getMessage());
		}
		return resp;
	}
	/**
	 * 查询虚拟机状态
	 * @param request
	 * @return
	 */
	@GET
	@Path("/QueryVMStatusReq")
	@Produces(MediaType.APPLICATION_JSON)
	public VMStatusResp QueryVMStatusReq(@Context HttpServletRequest request) {
		String VMID = request.getParameter("VMID");
		
		System.out.println("VMID=" + VMID);
		
		//实例化返回值对象
		VMStatusResp vMStatusResp = new VMStatusResp(); 
		try{
			//登录认证
			OSClientV2 os = OSFactory.builderV2()
	                .endpoint("http://10.50.0.11:5000/v2.0")
	                .credentials("admin","ADMIN_PASS")
	                .tenantName("admin")
	                .authenticate();
			
			
			// list server by id
			Server server = os.compute().servers().get(VMID);
			
			
			
			//定义一个变量，并进行判断来设置返回内容
			int tmp = 0;
			if(server.getVmState() != "active"){
				tmp = 1;
			}else{
				tmp = 2;
			}
			
			//设置返回值
	        vMStatusResp.setOperationIP(server.getAccessIPv4());
	        vMStatusResp.setStatus(tmp);
	        vMStatusResp.setVMID(server.getId());
	        vMStatusResp.setVlanID(server.getTenantId());
	        
	        //返回对象值
			return vMStatusResp;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			vMStatusResp.setFaultstring(e.getMessage());
		}
		return vMStatusResp;
	}
	/**
	 * 备份虚拟机
	 * @param request
	 * @return
	 */
	@GET
	@Path("/BackupVMReq")
	@Produces(MediaType.APPLICATION_JSON)
	public BaseResp BackupVMReq(@Context HttpServletRequest request) {
		String VMID = request.getParameter("VMID");
		
		System.out.println("VMID=" + VMID);
		
		//实例化返回值对象
		BaseResp baseResp = new BaseResp();
		
		
		try{
			//登录
			OSClientV2 os = OSFactory.builderV2()
	                .endpoint("http://10.50.0.11:5000/v2.0")
		            .credentials("admin","ADMIN_PASS")
		            .tenantName("admin")
		            .authenticate();
			
			// 开始备份虚拟机
			Server server = os.compute().servers().get(VMID);
			
			//定义一个变量，并进行判断返回值内容
			String result;
			if(server.getVmState() == "active"){
				String imageId = os.compute().servers().createSnapshot(server.getId(), server.getName()+"备份");
				result = "成功备份虚拟机 " + imageId;
			}else{
				result = "无法备份虚拟机" + server.getId();
			}
			
			
			//设置返回值内容
			baseResp.setFaultstring(result);
			//返回对象
			return baseResp;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			baseResp.setFaultstring(e.getMessage());
		}
		return baseResp;
	}
}
